package com.banyou.banyou.base;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;

import butterknife.ButterKnife;

/**
 * Created by gxy on 2016/8/15.
 */
public abstract class BaseFragment<P extends BasePresenter> extends Fragment {
    protected P mPresenter;
    public View mLayoutView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mPresenter = initPresenter();
        mLayoutView = inflater.inflate(setLayoutId(), container, false);
        ButterKnife.bind(this, mLayoutView);
        init();
        init(savedInstanceState);
        return mLayoutView;
    }

    protected abstract void init();

    protected void init(Bundle savedInstanceState) {
    }

    protected abstract int setLayoutId();

    protected abstract P initPresenter();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.destoryPresenter();
            mPresenter = null;
        }
    }

    public void requestFail(Throwable e, String error) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            ShowToast.showToast(error);
        }
    }

    public SharedPreferences getSharedPreference(){
        SharedPreferences preferences=getActivity().getSharedPreferences("login", Activity.MODE_PRIVATE);
        return preferences;
    }
}
